<template>
	<view>
		<view class="header-searccon" :style="{height: `${statusBarHeight}px`}">
			<view class="header-search widthWpApp" :style="{paddingTop: `${paddingTop}px`}">
					<uni-icons type="left" size="25"  @tap="BackPage" v-if="isNotBack" color="#000"></uni-icons>
					<view class="header-conLeft cuIcon-home-left" @tap="GoHome" v-else-if="!isNotBack">
						<text class="cuIcon-home"></text>
					</view>
					<view class="input-container">
						<view class="uni-icons-left">
							<uni-icons type="search"  size="18" color="#A3A3A3"></uni-icons>
						</view>
						<view class="input-con">
							<input type="text" class="uni-icons-leftinput" @input="inputSearch" v-model.trim="kw" :placeholder="placeholder" @confirm="searchConfirm">
						</view>
						<text class="header-btn" @click="searchBoxHandler">搜索</text>
						<view class="header-delete" style="right: 120rpx;z-index: 99999999;" v-if="showInput" @tap="removeText">
							<uni-icons type="closeempty"  size="20" color="#A3A3A3"></uni-icons>
						</view>
					</view>
			</view>
		</view>
		<view class="search-history" v-if="historyList.length > 0">
			<view class="search-history-title history-title">
				<text>搜索历史</text>
				<uni-icons type="trash" size="17" color="#8f8f8f" @click="cleanHistory"></uni-icons>
			</view>
			<view class="search-history-li">
				<block v-for="(item,index) in historys" :key="index">
					<text class="search-history-liText" @tap="searchTextBtn(item)" >{{item}}</text>
				</block>
			</view>
		</view>
	</view>
</template>

<script>
	import { getSearchList } from '@/api/goodscategory.js'
	export default {
		name:"search-header",
		data() {
			return {	
				statusFlag:true, // 是否有搜索结果
				// 微信小程序的胶囊的高度
				statusBarHeight: "",
				paddingTop:"",
				placeholder:'净水服务',
				isNotBack: true,
				
				showInput: false, //输入框内的删除
				
				// 搜索结果列表
				searchResults: [],
				
				// 延时器的 timerId
				timer: null,
				// 搜索关键词
				kw: '',
				
				// 搜索关键词的历史记录
				historyList:JSON.parse(uni.getStorageSync('kw') || '[]'),
				
				hasEnoughData: false,
				
				
			};
		},
		onLoad() {
			
		},
		methods:{
			searchConfirm(){
				this.searchBoxHandler()
			},
			BackPage() {
				uni.navigateBack({
					delta: 1
				});
			},
			GoHome() {
				uni.switchTab({
					url: '/pages/home/index'
				});
			},
			removeText(){
				this.kw = ''
				this.showInput = false
				console.log('123')
			},
			searchBoxHandler(){
				// 判断关键词是否为空
				 if (this.kw === '') {
					this.kw = this.placeholder
					this.showInput = true
				 	// this.searchResults = []
				 	// return
				}
				
				this.getSearchData({name:this.kw})
				this.saveSearchHistory()
			},
			searchTextBtn(item){
				const o = {
					name:item
				}
				console.log(o)
				this.getSearchData(o)
			},
			inputSearch(e){
				//清除timer 对应的定时器
				clearTimeout(this.timer)
				
				//重新启动一个定时器,并把timerId赋值给this.timer
				
				this.timer = setTimeout(()=>{
					
					// 如果 500 毫秒内，没有触发新的输入事件，则为搜索关键词赋值
					
					this.kw = e.target.value
					
					// // 根据关键词，查询搜索建议列表
					// this.getSearchData({name:this.kw})
					// 判断关键词是否为空
					 if (this.kw === '') {
						this.showInput = false
					 	this.searchResults = []
					 	return
					}else{
						this.showInput = true		
					}
					
					// 1. 查询到搜索建议之后，调用 saveSearchHistory() 方法保存搜索关键词
					this.saveSearchHistory()
					
				},500)
				
			},
			async getSearchData(obj){
				// 判断关键词是否为空
			  //   if (this.kw === '') {
					// this.searchResults = []
					// return
			  //   }
			
				const { data,msg } = await getSearchList(obj)
				
				
				this.statusFlag = msg
			
				this.searchResults = data.records
				// console.log(data)
				this.$emit('search-results-updated',{ statusFlag: this.statusFlag, searchResults: this.searchResults });
				
					
			},
			// 2. 保存搜索关键词的方法
		    saveSearchHistory() {
				 // 检查搜索关键词是否为空或只包含空格
				  if (!this.kw || /^\s*$/.test(this.kw)) {
				    return; // 不执行保存搜索历史记录的逻辑
				  }

				// 2.1 直接把搜索关键词 push 到 historyList 数组中
				// this.historyList.push(this.kw)
				// 解决关键词重复的问题
				const set = new Set(this.historyList)  //将 Array 数组转化为 Set 对象
				
				set.delete(this.kw)  //调用 Set 对象的 delete 方法，移除对应的元素
				
				set.add(this.kw)  //调用 Set 对象的 add 方法，向 Set 中添加元素
				
				this.historyList  = Array.from(set)     // 将 Set 对象转化为 Array 数组
				
				// 持久化存储到本地
				
				uni.setStorageSync('kw',JSON.stringify(this.historyList))
		    },
			// 清空搜索历史记录
			cleanHistory() {
			  // 清空 data 中保存的搜索历史
			  this.historyList = []
			  // 清空本地存储中记录的搜索历史
			  uni.setStorageSync('kw', '[]')
			}
			
		},
		computed:{
			// 关键词前后顺序的问题
			historys(){
				return [...this.historyList].reverse()
			}
		},
		mounted: function() {
			let pages = getCurrentPages()
			/**
			 * 判断是否能返回
			 */
			if (pages.length <= 1 || pages[pages.length - 1].route == 'pages/login/index') {
				this.isNotBack = false
			} else {
				this.isNotBack = true
			}
		},
		beforeMount() {
			// #ifdef MP-WEIXIN
			let custom = wx.getMenuButtonBoundingClientRect();
			wx.getSystemInfo({
			    success: res=>{
					// console.log(res.statusBarHeight);
					this.statusBarHeight = (res.statusBarHeight + (custom.top - res.statusBarHeight)) * 1.2 + custom.height;
					// console.log(custom.top+ '*****')
					// console.log(custom.height+ '*****')
					this.paddingTop = (res.statusBarHeight) - 10
				}
			});
			// #endif
		},
	}
</script>

<style lang="scss">
 /* #ifdef MP-WEIXIN */
 .cuIcon-home-left{
	 margin-right: 10px;
	 margin-left: 10px;
 }
 /* #endif */
 /* #ifdef  APP-PLUS || H5 */
 .cuIcon-home-left{
 	 margin-right: 10px;
 }
  /* #endif */
.cuIcon-home{
	color: #000;
	font-weight: 400;
	font-size: 20px;
	
}
 /* #ifdef MP-WEIXIN */
 .widthWpApp{
	 width: 77.5%;
 }
 
/* #endif */
 
/* #ifdef  APP-PLUS || H5 */
 .widthWpApp{
 	 width: 95%;
	 margin: 0 auto;
 }
/* #endif */
  
page{
	background-color: #f8f8f8;
}
.header-searccon{
		padding: 15px 0;
		background-color: #fff;
}
.header-search{
	display: flex;
	align-items: center;
	position: sticky;
	top: 0;
	z-index: 999;
	.input-container{
		display: flex;
		position: relative;
		width: 100%;
		align-items: center;
		.uni-icons-left{
			position: absolute;
			left: 20.5rpx;
		}
		.input-con{
			width: 100%;
			height: 60rpx;
			background: #F5F5F5;
			border-radius: 29rpx;
			line-height: 60rpx;
			.uni-icons-leftinput{
				width: 100%;
				height: 60rpx;
				padding-left: 67.5rpx;
				color: #333;
				font-size: 26rpx;
			}
		}
		.header-btn{
			color: #fff;
			z-index: 99999;
			font-size: 30rpx;
			margin-left: 10px;
			position: absolute;
			right: 0;
			background-color: #18B1BB;
			width: 110rpx;
			display: block;
			height: 60rpx;
			font-size: 26rpx;
			line-height: 60rpx;
			text-align: center;
			border-top-right-radius: 29rpx; /* 设置右上角的圆角半径为 29rpx 像素 */
			border-bottom-right-radius: 29rpx; /* 设置右下角的圆角半径为 29rpx 像素 */
		}
	}
}
.search-history-title{
	font-size: 28rpx;
	color: #8F8F8F;
	padding: 12rpx 0 24rpx;
}
.search-history{
	margin: 0 auto;
	width: 95%;
	.search-history-li{
		display: flex;
		flex-wrap: wrap;
	    // justify-content: flex-start;
		.search-history-liText{
			margin-bottom: 8px;
			width: 23.5%;
			height: 60rpx;
			background: #FFFFFF;
			border-radius: 12rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 26rpx;
			color: #000;
			margin-left: 2%;
			&:nth-child(4n-3){
				margin-left: 0;
			}
		}
	}
}
.history-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 40px;
    font-size: 13px;
}
.header-delete{
	position: absolute;
}
</style>